package com.kaifamiao.trace;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.logging.Logger;

@WebServlet( "/session/counter" )
public class SessionCounterServlet extends HttpServlet {
    private Logger logger = Logger.getLogger( this.getClass().getName() );

    @Override
    protected void service(HttpServletRequest request , HttpServletResponse response )
            throws ServletException, IOException {
        String cookie = request.getHeader( "cookie" );
        logger.info( "从请求中获取到的cookie: " + cookie );
        logger.info( "获得与当前请求管理的会话对象" );
        HttpSession session = request.getSession();
        logger.info( "Session ID: " + session.getId() );
        logger.info( "Session Is New: " + session.isNew() );

        // 首先尝试从 会话对象 中获取名称是 counter 的属性值
        Integer counter = (Integer) session.getAttribute( "counter" );
        // 若 counter 不存在，则指定一个起始值
        if( counter == null ) {
            counter = 0 ; // auto-boxing
        }
        // 最后将新的值重新放入到 会话对象 中
        session.setAttribute( "counter" , ++counter );

        // 设置响应头中 content-type 字段的值
        response.setContentType( "text/html;charset=UTF-8" );
        // 获得可以向 "响应对象" 中输出字符数据的打印流
        PrintWriter out = response.getWriter();
        // 向 "响应对象" 中输出字符数据
        out.println( "<h3 style='text-align:center;'>" );
        out.println( counter );
        out.println( "</h3>" );

    }
}
